﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Web;
using System.Xml;
using System.Xml.XPath;

using umbraco.BusinessLogic;
using umbraco.cms.businesslogic.property;
using umbraco.BusinessLogic.Actions;
using umbraco.interfaces;
using umbraco.cms.businesslogic.web;
using System.Configuration;
using System.IO;

namespace FMAutoTweet
{
    class AutoTweet : IActionHandler
    {

        private static String twitterUrl = "http://twitter.com/statuses/update.xml";
        private static String pluginName = "FM Auto Tweet";
        private static String appVPath = @"\plugins\FergusonMoriyama\AutoTweet\";
        private static String configFileName = "twitter.config";
        private static bool logEnabled = true;

        string IActionHandler.HandlerName()
        {
            return "FergusonMoriyama.Umbraco.FMAutoTweet.AutoTweet";
        }

        IAction[] IActionHandler.ReturnActions()
        {
            return new IAction[] { new ActionPublish() };
            
        }

        protected void log(LogTypes l, String m)
        {
            if (logEnabled || l == LogTypes.Error)
            {
                Log.Add(l, -1, pluginName + ": " + m);
            }
        }

        Boolean IActionHandler.Execute(Document doc, IAction action)
        {

            log(LogTypes.Debug, "Tweet action fired.");
            // doc.GetVersions().Length
            String umbracoVPath = ConfigurationManager.AppSettings["umbracoPath"];
            String umbracoPhysicalPath = HttpContext.Current.Server.MapPath(umbracoVPath) + appVPath;
            String configFile = Path.Combine(umbracoPhysicalPath, configFileName);

            log(LogTypes.Debug, configFile);

            if (File.Exists(configFile))
            {
                String thisAlias = doc.ContentType.Alias.ToLower();
                log(LogTypes.Debug, "alias: " + thisAlias);

                XPathDocument Doc = new XPathDocument(configFile);
                XPathNavigator navigator = Doc.CreateNavigator();

                try
                {
                    String uid = navigator.SelectSingleNode("/config/authentication/username").Value;
                    log(LogTypes.Debug, "uid: " + uid);
                    String pwd = navigator.SelectSingleNode("/config/authentication/password").Value;

                    XPathNodeIterator iterator = navigator.Select("/config/doctypes/doctype");
                    while (iterator.MoveNext())
                    {
                        log(LogTypes.Debug, "iterate");

                        String alias = iterator.Current.SelectSingleNode("alias").Value.ToLower();
                        log(LogTypes.Debug, "cmp: " + alias + " " + thisAlias);

                        if(thisAlias.Equals(alias))
                        {

                            String titlePropertyAlias = iterator.Current.SelectSingleNode("titlePropertyAlias").Value;
                            String url = umbraco.library.NiceUrl(doc.Id);
                            if (url.IndexOf("/") == 0) { url = url.Substring(1); }

                            Uri u = HttpContext.Current.Request.Url;
                            String baseUrl = u.Scheme + "://" + u.Host + ":" + u.Port + "/";
                            url = baseUrl + url;

                            String message = iterator.Current.SelectSingleNode("message").Value + " " + url;
                            
                            String title = (String) doc.getProperty(titlePropertyAlias).Value;

                            message = message.Replace("{title}", title);

                            WebRequest request = WebRequest.Create(twitterUrl);
                            request.Headers.Add("X-Twitter-Client", "AutoTweet for Umbraco");
                            request.Headers.Add("X-Twitter-Version", "1.0");
                            request.Headers.Add("X-Twitter-URL", "http://www.darren-ferguson.com/");

                            request.Credentials = new NetworkCredential(uid, pwd);
                            request.ContentType = "application/x-www-form-urlencoded";
                            request.Method = "POST";

                            message = "status=" + HttpUtility.UrlEncode(message);

                            byte[] bytes = Encoding.UTF8.GetBytes(message);

                            request.ContentLength = bytes.Length;
                            using (Stream requestStream = request.GetRequestStream())
                            {
                                requestStream.Write(bytes, 0, bytes.Length);

                                using (WebResponse response = request.GetResponse())
                                {
                                    using (StreamReader reader = new StreamReader(response.GetResponseStream()))
                                    {
                                        String result = reader.ReadToEnd();
                                        result = result.Replace("<", "&lt;");
                                        result = result.Replace(">", "&gt;");
                                        log(LogTypes.Debug, "Twitter says: " + result);
                                    }
                                }
                            }
                        }
                    }

                }
                catch (Exception ex)
                {

                    Log.Add(LogTypes.Error, -1, ex.Message);
                    return false;
                }


            }
            else
            {
                log(LogTypes.Error, configFile + "not found.");
            }
            return true;
        }
    }
}
